/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86187
 * Date: 2022-05-24
 * Time: 21:51
 */

public class TestList {

    /**
     * 给你单链表的头指针 head 和两个整数left 和 right ，其中left <= right 。
     * 请你反转从位置 left 到位置 right 的链表节点，返回 反转后的链表 。
     * @param head 链表头节点
     * @param left 范围的左边界
     * @param right 右边界
     * @return head->头节点
     */
    public static Node reverseBetween(Node head, int left, int right) {
        if(head == null || head.next == null || right == left) {
            return head;
        }

        Node leftNode = head;
        Node prev = leftNode;
        while(left-1 != 0 && leftNode.next != null) {
            prev = leftNode;
            leftNode = leftNode.next;
            left--;
        }

        Node rightNode = head;
        while(right-1 != 0 && rightNode.next != null) {
            rightNode = rightNode.next;
            right--;
        }

        Node isHead = leftNode;
        Node tail = rightNode.next;
        Node pos = leftNode.next;
        Node cur = pos.next;

        while(pos != tail) {
            pos.next = leftNode;
            leftNode = pos;
            pos = cur;
            if(cur != null)
                cur = cur.next;
        }

        if(isHead == head) {
            head = rightNode;
        } else {
            prev.next = rightNode;
        }
        isHead.next = tail;

        return head;

    }


    public static void main(String[] args) {
        ListNode listNode = new ListNode();

        listNode.addLast(1);
        listNode.addLast(2);
        listNode.addLast(3);
        listNode.addLast(4);
        listNode.addLast(5);

        Node pHead = reverseBetween(listNode.head,2,4);

        listNode.display(pHead);
    }
}
